//
//  UIView+Tap.m
//  Express
//
//  Created by lhongl on 2025/9/26.
//  Copyright © 2025 QM. All rights reserved.
//

#import "UIView+Tap.h"
#import <objc/runtime.h>

static const void* tagValue = &tagValue;

@interface UIView ()

// 事件
@property (nonatomic, copy) void(^tapAction)(id);

@end
@implementation UIView (Tap)

#pragma mark 添加事件
- (void)addTapBlock:(void(^)(id obj))tapAction{
    [self addTapWithTapsRequired:1 touchesRequired:1 block:tapAction];
}

- (void)addTarget:(id)target action:(SEL)action{
    [self addTarget:target tapsRequired:1 touchesRequired:1 action:action];
}

- (void)addTapWithTapsRequired:(NSInteger)numberOfTaps block:(void(^)(id obj))tapAction {
    [self addTapWithTapsRequired:numberOfTaps touchesRequired:1 block:tapAction];
}

- (void)addTarget:(id)target tapsRequired:(NSInteger)numberOfTaps action:(SEL)action {
    [self addTarget:target tapsRequired:numberOfTaps touchesRequired:1 action:action];
}


- (void)addTapWithTapsRequired:(NSInteger)numberOfTaps touchesRequired:(NSInteger)numberOfTouches block:(void(^)(id obj))tapAction {
    if (!tapAction || [self gestureRecognizers]) {
        return;
    }
    self.tapAction = tapAction;
    [self addTarget:self tapsRequired:numberOfTaps touchesRequired:numberOfTouches action:@selector(tapGestureAction)];
}

- (void)addTarget:(id)target tapsRequired:(NSInteger)numberOfTaps touchesRequired:(NSInteger)numberOfTouches action:(SEL)action {
    if (!target || !action || [self gestureRecognizers]) {
        return;
    }
    self.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:target action:action];
    tap.numberOfTapsRequired = numberOfTaps;
    tap.numberOfTouchesRequired = numberOfTouches;
    [self addGestureRecognizer:tap];
}

#pragma mark 添加事件
- (void)tapGestureAction{
    if (self.tapAction) {
        self.tapAction(self);
    }
}

#pragma mark - setter & getter
-(void)setTapAction:(void (^)(id))tapAction {
    objc_setAssociatedObject(self, tagValue, tapAction, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
-(void (^)(id))tapAction {
    return objc_getAssociatedObject(self, tagValue);
}

@end
